<template>
  <div class="create-container">
    <div v-if="authGroupOptions && authGroupOptions.length === 0 && !loading">
      <el-result
        icon="error"
        title="无权限访问"
        sub-title="无权限进行操作，请联系管理员"
      />
    </div>
    <div v-else>
      <el-row
        class="header"
        type="flex"
        justify="center"
        align="middle"
      >
        <el-col
          :span="18"
          :offset="2"
        >
          <el-select
            class="select-width"
            v-model="currentAuthGroup"
            value-key="value"
            placeholder="请选择权限组"
            @change="dataTableKey = new Date().getTime()"
          >
            <el-option
              v-for="item in authGroupOptions"
              :key="item.value"
              :label="item.label"
              :value="item"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button
            circle
            icon="ele-HomeFilled"
            size="default"
            type="primary"
            @click="$router.push('/')"
          />
        </el-col>
      </el-row>
      <div v-if="currentAuthGroup && currentAuthGroup.value === 'submit'">
        <el-scrollbar height="calc(100vh - 50px)">
          <WritePage :write-type="2" />
        </el-scrollbar>
      </div>
      <div v-else>
        <DataTable
          v-if="currentAuthGroup"
          :mode="2"
          :key="dataTableKey"
          :auth-group="currentAuthGroup.auth"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="DataCreate">
import { getFormUserAuthRequest } from "@/api/project/publish";
import { defineAsyncComponent, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import WritePage from "../write/index.vue";
import { getProjectRequest } from "@/api/project/form";
import { useFormInfo } from "@/stores/formInfo";
import {NextLoading} from "@/utils/loading";

const DataTable = defineAsyncComponent(() => import("./index.vue"));
const currentAuthGroup = ref<any>(null);
const authGroupOptions = ref<Array<{ value: string; label: string; auth?: any }>>([]);
const formKey = ref<string | undefined>("");
const loading = ref(true);
const selectId = ref<string | null>(null);
const dataTableKey = ref<number>(100);

const route = useRoute();

const formInfo = useFormInfo();

onMounted(async () => {
  NextLoading.done(600);
  formKey.value = (route.query.key || route.params.key) as string;
  selectId.value = (route.query.gid || route.params.gid) as string;

  getProjectRequest(formKey.value).then((res: any) => {
    formInfo.setFormType(res.data.type);
  });

  try {
    const res = await getFormUserAuthRequest(formKey.value);
    if (!res.data) {
      loading.value = false;
      return;
    }

    // 检查是否有新增的权限 无权限则进入
    const isAdd = res.data.some((item: any) => item.btnPerms.includes("add"));
    let defaultOptions = [];
    if (isAdd) {
      defaultOptions = [
        {
          value: "submit",
          label: "提交"
        }
      ];
    }

    authGroupOptions.value = defaultOptions.concat(
      res.data.map((item: any) => ({
        value: item.id,
        label: item.name,
        auth: item
      }))
    );

    // 默认选中第一个
    if (authGroupOptions.value.length > 0) {
      currentAuthGroup.value = authGroupOptions.value[0];
    }

    // 默认选中权限组
    if (selectId.value) {
      currentAuthGroup.value = authGroupOptions.value.find((item: any) => item.value + "" === selectId.value);
    }
  } catch (error) {
    console.error("Error fetching user auth:", error);
  } finally {
    loading.value = false;
  }
});
</script>

<style lang="scss" scoped>
.create-container {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;

  .header {
    height: 50px;
    box-shadow:
      0 2px 4px rgba(0, 0, 0, 0.12),
      0 0 6px rgba(0, 0, 0, 0.04);
  }
}
</style>
